/**
 * ChaShaKu GUI
 * @author Yusak Taniguchi
 */
Ext.app.Grid = {
	tagKeys:['surface','reading','pronunciation','part_of_speech','ctype','cform'],
	tagConditons: {
		surface:true,
		reading:false,
		ponunciation:false,
		part_of_speech:false,
		ctype:false,
		cform:false
	},
	PagingToolbar:{
		create: function(ds){
			return new Ext.PagingToolbar({
				pageSize: 25,
				store: ds,
				displayInfo: true,
				displayMsg: 'Displaying topics {0} - {1} of {2}',
				emptyMsg: "No topics to display"
			});
		}
	},
	addAroundSearchMenu: function(grid,tabPanel){
		var size = new Ext.form.NumberField({
			disabled: true,
			allowBlank: false,
			allowDecimals: false, 
			allowNegative: false,
			maxValue: 100,
			minValue: 1,
			value: 25,
			width: 25
		});
		var sm = grid.getSelectionModel();
		var searchAroundSentences = function(){
			if (size.validate()) {
				var rows = sm.getSelections();
				rows.each(function(record){
					var id = record.get('id');
					var load_size = size.getValue();
					var p = tabPanel.add({
						title: String.format('{0} Sentences (id:{1})',load_size,id),
						iconCls: 'manual',
						autoLoad:{
							url: 'optimized_search/around_sentences',
							params: {id: id, size: load_size },
    						timeout: 30,
							scripts:true
						},
						autoScroll:true,
						closable:true
					});
					tabPanel.setActiveTab(p);
				});
			}
		}
		var show = new Ext.Toolbar.Button({
			iconCls: 'manual',
			disabled: true,
			handler: searchAroundSentences,
			text: "Show"
		});
		size.on('specialkey',function(field,e){
			if (size.validate()) {
				switch (e.getKey()) {
					case Ext.EventObject.ENTER:
						searchAroundSentences();
						break;
					case Ext.EventObject.UP:
						var value = size.getValue();
						if(value < 100){
							size.setValue(value + 1);
						}
						break;
					case Ext.EventObject.DOWN:
						var value = size.getValue();
						if(value > 1){
							size.setValue(value - 1);
						}
						break;
				}
			}
		});
		sm.on({
			rowselect: function(){
				if(size.disabled || show.disabled){
					size.enable();
					show.enable();
				}
			},
			rowdeselect: function(){
				if(!sm.hasSelection()){
					show.disable();
					size.disable();
				}
			},
			scope: this
		});
		var ds = grid.getStore();
		ds.on({
			load: function(){
				if(!sm.hasSelection()){
					show.disable();
					size.disable();
				}
			} 
		});
		var pbar = grid.getBottomToolbar();
		pbar.add('-',' ',show,'around',size,'sentences');
	},
	ListColumnModel:{
		create: function(center_uniq){
			var columns;
			if(center_uniq){
				columns = [
					{	header: "Center",
				        dataIndex: 'center',
						sortable: true,
						align : 'center'
					},
					{  	header: "Count Size",
			           	dataIndex: 'count',
						sortable: true,
						align : 'left'
			        }]				
			}else{
				columns = [
					{  	header: "Left side",
				       	dataIndex: 'left_side',
						sortable: true,
						align : 'right'
					},
					{	header: "Center",
				        dataIndex: 'center',
						sortable: true,
						align : 'center'
					},
					{  	header: "Right side",
			           	dataIndex: 'right_side',
						sortable: true,
						align : 'left'
			        },
					{  	header: "Count Size",
			           	dataIndex: 'count',
						sortable: true,
						align : 'left'
			        }]
			}			
			return new Ext.grid.ColumnModel(columns);
		}
	},
	SequenceListColumnModel:{
		create: function(keywords){
			var renderColumn = function(content,metadata,record,row_index,column_index){
				var text = ''
				Ext.app.Grid.tagKeys.each(function(key,index){
					td = String.format('<td style=\'text-align:center;white-space: nowrap;\'>{0}</td>',(content.hasOwnProperty(key) ? content[key] : ''));
					if (Ext.app.Grid.tagConditons[key]) {
						text += String.format('<tr class=\'{0}\'>{1}</tr>', key, td);
					}else {
						text += String.format('<tr class=\'{0}\' style=\'display:none;\'>{1}</tr>', key, td);
					}
				});
				return String.format('<table align=\'center\'>{0}</table>',text);
			};
			var columns = []
			keywords.each(function(keyword,index){
				columns.push({
				  	header: Ext.util.JSON.encode(keyword),
			       	dataIndex: 'word' + index,
					sortable: true,
				   	renderer: renderColumn,
					align : 'center'
				});				
			});
			columns.push({
			  	header: "Count Size",
			    dataIndex: 'count',
				sortable: true,
				align : 'left'
		    });	
			return new Ext.grid.ColumnModel(columns);
		}
	},
	SequenceCenterListColumnModel:{
		create: function(keywords){
			var renderColumn = function(content,metadata,record,row_index,column_index){
				var text = ''
				Ext.app.Grid.tagKeys.each(function(key,index){
					td = String.format('<td style=\'text-align:center;white-space: nowrap;\'>{0}</td>',(content.hasOwnProperty(key) ? content[key] : ''));
					if (Ext.app.Grid.tagConditons[key]) {
						text += String.format('<tr class=\'{0}\'>{1}</tr>', key, td);
					}else {
						text += String.format('<tr class=\'{0}\' style=\'display:none;\'>{1}</tr>', key, td);
					}
				});
				return String.format('<table align=\'center\'>{0}</table>',text);
			};
			var columns = [{
				  	header: Ext.util.JSON.encode(keywords.first()) + " (Center)" ,
			       	dataIndex: 'center',
					sortable: true,
				   	renderer: renderColumn,
					align : 'center'
				},
				{
				  	header: "Count Size",
				    dataIndex: 'count',
					sortable: true,
					align : 'left'
		    }]
			return new Ext.grid.ColumnModel(columns);
		}
	},
	SentenceColumnModel: {
		create: function(expander){
			var renderColumn = function(content,metadata,record,row_index,column_index){
				var text = '';
				var aligns = ['right','center','left'];
				Ext.app.Grid.tagKeys.each(function(key,index){
					var flag = content.any(function(value){
						return value.hasOwnProperty(key);
					});
					if(flag){
						var last_word_index = content.length - 1;
						var tds= content.map(function(value,index){
							if(index < last_word_index){
								return String.format('<td style=\'text-align:center;border-right: 1px #A3A3A3 dashed;white-space: nowrap;\'>{0}</td>',(value[key] ? value[key] : ''));
							}else{
								return String.format('<td style=\'text-align:center;white-space: nowrap;\'>{0}</td>',(value[key] ? value[key] : ''));
							}
							
						});
						if(Ext.app.Grid.tagConditons[key]){
							text += String.format('<tr class=\'{0}\' >{1}</tr>',key,tds.join(''));
						} else{
							text += String.format('<tr class=\'{0}\' style=\'display:none;\'>{1}</tr>',key,tds.join(''));
						}
					}
				});
				return String.format('<table align=\'{0}\'>{1}</table>',aligns[column_index],text);
			};
			return new Ext.grid.ColumnModel([
					{  	header: "Left side",
				       	dataIndex: 'left_side',
					   	renderer: renderColumn,
						sortable: true,
						width: 0.42
					},
					{	header: "Center",
				        dataIndex: 'center',
						renderer: renderColumn,
						sortable: true,
						width: 0.16
					},
					{  	header: "Right side",
					   	renderer: renderColumn,
			           	dataIndex: 'right_side',
						sortable: true,
						width: 0.42
			        }
			])
		}
	},
	PropertyColumnModel:{
		create: function(){
			return new Ext.grid.ColumnModel([
				new Ext.grid.CheckColumn({
			       header: "KWIC Center",
			       dataIndex: 'center_word',
			       width: 90,
				   editor: new Ext.form.Checkbox({})
			    }),
				{
		        	header: "Surface",
		        	dataIndex: 'surface',
					width: 80,
		        	editor: new Ext.form.TextField({})
		        },{
		        	header: "Reading",
		        	dataIndex: 'reading',
					width: 80,
		        	editor: new Ext.form.TextField({})
		        },{
		        	header: "Base form",
		        	dataIndex: 'basetype_surface',
					width: 120,
		        	editor: new Ext.form.TextField({})
		        },{
		        	header: "Part of speech",
		        	dataIndex: 'part_of_speech',
					width: 200,
		        	editor: new Ext.form.ComboBox({
				        store: Ext.app.Data.POS,
				        displayField:'item',
						autoWidth: true,
				        mode: 'local',
				        triggerAction: 'all',
				        emptyText:'Select a item...'
				    })
		        },{
		        	header: "Conjugation type",
		        	dataIndex: 'ctype',
					width: 200,
		        	editor: new Ext.form.ComboBox({
				        store: Ext.app.Data.Ctype,
				        displayField:'item',
						autoWidth: true,
				        mode: 'local',
				        triggerAction: 'all',
				        emptyText:'Select a item...'
				    })
		        },{
		        	header: "Conjugated form",
		        	dataIndex: 'cform',
					width: 200,
		        	editor: new Ext.form.ComboBox({
				        store: Ext.app.Data.Cform,
				        displayField:'item',
						autoWidth: true,
				        mode: 'local',
				        triggerAction: 'all',
				        emptyText:'Select a item...'
				    })
		        },{
		        	header: "Interval",
		        	dataIndex: 'interval',
							width: 80,
		        	editor: new Ext.form.TextField({})
		        }
			]);
		}
	},
	KWICGrid: {
		create: function(text,ds){
			var expander = new Ext.grid.RowExpander({
				tpl : new Ext.Template(
					'<p><b>[id]</b> {id}</p>',
					'<p><b>[sentence]</b><br>{text}</p>'
				)
			});
			return new Ext.grid.GridPanel({
				iconCls: 'find',
				title:text,
				closable: true,
				store: ds,
				autoScroll : true,
		        collapsible: true,
		        animCollapse: false,
				plugins: expander,
				colModel: Ext.app.Grid.SentenceColumnModel.create(expander),
				selModel: new Ext.grid.RowSelectionModel({singleSelect: true }),
			    viewConfig: {
			        forceFit: true,
					emptyText: '<table width=100% height=100% ><tr valign=middle align=center ><td>no topics</td></tr></table>'
			    },
				loadMask: true,
				bbar: Ext.app.Grid.PagingToolbar.create(ds)
			});
		}
	},
	List: {
		create: function(text,ds,center_uniq){
			var sm = center_uniq ? new Ext.grid.RowSelectionModel({singleSelect:false}) : new Ext.grid.RowSelectionModel({singleSelect:true});
			return new Ext.grid.GridPanel({
				iconCls: 'wordList',
				title:text,
				closable: true,
				store: ds,
				autoScroll : true,
				colModel : Ext.app.Grid.ListColumnModel.create(center_uniq),
				selModel : sm,
			    viewConfig: {
			        forceFit: true,
					emptyText: '<table width=100% height=100% ><tr valign=middle align=center ><td>no topics</td></tr></table>'
			    },
				loadMask: true,
				bbar: Ext.app.Grid.PagingToolbar.create(ds)
			});
		}
	},
	SequenceCenterList: {
		create: function(text,ds,keywords){
			return new Ext.grid.GridPanel({
				iconCls: 'wordList',
				title:text,
				closable: true,
				store: ds,
				autoScroll : true,
				colModel : Ext.app.Grid.SequenceCenterListColumnModel.create(keywords),
			    viewConfig: {
			        forceFit: true,
					emptyText: '<table width=100% height=100% ><tr valign=middle align=center ><td>no topics</td></tr></table>'
			    },
				loadMask: true,
				bbar: Ext.app.Grid.PagingToolbar.create(ds)
			});
		}
	},
	SequenceList: {
		create: function(text,ds,keywords){
			return new Ext.grid.GridPanel({
				iconCls: 'wordList',
				title:text,
				closable: true,
				store: ds,
				autoScroll: true,
				colModel : Ext.app.Grid.SequenceListColumnModel.create(keywords),
			    viewConfig: {
			        forceFit: true,
					emptyText: '<table width=100% height=100% ><tr valign=middle align=center ><td>no topics</td></tr></table>'
			    },
				loadMask: true,
				bbar: Ext.app.Grid.PagingToolbar.create(ds)
			});
		}
	},
	GroupingList: {
		create: function(text,ds,center_uniq){
			return new Ext.grid.GridPanel({
				iconCls: 'wordList',
				title:text,
				closable: true,
				store: ds,
				autoScroll : true,
				colModel : Ext.app.Grid.ListColumnModel.create(center_uniq),
				view: new Ext.grid.GroupingView({
				    forceFit:true,
				    groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})',
					emptyText: '<table width=100% height=100% ><tr valign=middle align=center ><td>no topics</td></tr></table>'
			    }),
				loadMask: true,
				bbar: Ext.app.Grid.PagingToolbar.create(ds)
			});
		}		
	},
	WordPropertyGrid:{
		create: function(ds){
			return new Ext.grid.EditorGridPanel({
				store: ds,
				colModel: Ext.app.Grid.PropertyColumnModel.create(),
				selModel: new Ext.grid.RowSelectionModel({singleSelect: true}),
				clicksToEdit: 1,
				autoScroll: true,
				autoDestroy: true,
				enableDragDrop: true,
				enableColumnMove: false,
				viewConfig: {
				    forceFit:true,
					emptyText: 'Please push "Add new keyword" button.'
			    },
				tbar: new Ext.Toolbar()
			});
		}
	},
	WordFormPanel:{
		create: function(word,wordProperties,root){
			var panel = wordProperties.add({
				title: word,
				closable: true,
				html: 'test'
			});
			wordProperties.setActiveTab(panel);
			var child = root.appendChild(new Ext.tree.TreeNode({
				text: word,
				leaf: true,
				icon: this.iconImg,
				propId: panel.getId()
			}));
			child.on('click',function(node){
				wordProperties.setActiveTab(node.attributes.propId);
			});
			panel.on('destroy',function(p){
				var node = root.findChild('propId',p.getId());
				node.remove();
			});
		},
		iconImg: 'images/arrow.png'
	}
}